using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using Microsoft.SharePoint;
using ShareTools.InfoPathFormsLib;
using ShareTools.Common;

namespace ShareTools.InfoPathFormsManager
{
    public partial class Form1 : Form
    {

        List<string> masterListForms = new List<string>();
        List<FormFeature> formFeatureList = new List<FormFeature>();
        string infoMessage = string.Empty;
        string wspName = "";
        string activationSiteUrl = "";

        public Form1()
        {
            InitializeComponent();
            grpOptions.Enabled = false;
            btnFormSpecificSettings.Enabled = false;
            linkLabel2.Links.Add(0, linkLabel2.Text.Length, "Help.txt");
        }

        #region Commented
        //private void button1_Click(object sender, EventArgs e)
        //{
        //    //FormsFeatureManager featureMgr1 = new FormsFeatureManager();
        //    //return;
        //    //ZipManager zipManager = new ZipManager();
        //    //zipManager.EnlistItems(@"C:\Advisor Portal\SampleIPWSP\Forms\Audit-trial1.cab");
        //    List<FormFeature> formsList = new List<FormFeature>();
        //    FormFeature form = new FormFeature();
        //    form.FormPath = @"C:\Advisor Portal\SampleIPWSP\Forms\Published\AuditTrailForm.xsn";
        //    form.HasCodeBehind = true;
        //    form.Title = (new System.IO.FileInfo(form.FormPath)).Name;
        //    form.Title = form.Title.Substring(0, form.Title.IndexOf("."));
        //    formsList.Add(form);

        //    form = new FormFeature();
        //    form.FormPath = @"C:\Advisor Portal\SampleIPWSP\Forms\Published\Dollar Exchange.xsn";
        //    form.HasCodeBehind = false;
        //    form.Title = (new System.IO.FileInfo(form.FormPath)).Name;
        //    form.Title = form.Title.Substring(0, form.Title.IndexOf("."));
        //    formsList.Add(form);

        //    form = new FormFeature();
        //    form.FormPath = @"C:\Advisor Portal\SampleIPWSP\Forms\Published\Dollar Cost Averaging.xsn";
        //    form.HasCodeBehind = false;
        //    form.Title = (new System.IO.FileInfo(form.FormPath)).Name;
        //    form.Title = form.Title.Substring(0, form.Title.IndexOf("."));
        //    formsList.Add(form);

        //    FormsFeatureManager featureMgr = new FormsFeatureManager();
        //    foreach (FormFeature formInfo in formsList)
        //    {
        //        featureMgr.ProcessForm(formInfo);                
        //    }
        //    featureMgr.RunWSPBuilder();
        //} 
        #endregion

        private void btnSelectForms_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.Filter = "InfoPath Forms (*.xsn)|*.xsn";
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.Multiselect = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    LoadMasterListOfForms(openFileDialog1.FileNames);
                    UpdateListItems();
                    FileInfo fileInfo = new FileInfo(openFileDialog1.FileName);
                    if (fileInfo == null || !fileInfo.FullName.EndsWith(".xsn"))
                    {
                        MessageBox.Show("Please pick a proper form template file.");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    //MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                    //rchTxtInformation.Text += Environment.NewLine + "Error: Could not read file from disk. Original error: " + ex.Message;
                }
            }
        }


        private void UpdateListItems()
        {
            listBoxForms.Items.Clear();
            foreach (string form in masterListForms)
            {
                listBoxForms.Items.Add(form.Substring(form.LastIndexOf("\\") + 1));
            }
        }

        private void LoadMasterListOfForms(string[] formsList)
        {
            masterListForms.Clear();
            for (int i = 0; i < formsList.Length; i++)
            {
                masterListForms.Add(formsList[i]); //.Substring(formsList[i].LastIndexOf("\\") + 1));
            }
        }

        private void RemoveForm()
        {
            if (listBoxForms.SelectedIndex >= 0)
            {
                masterListForms.RemoveAt(listBoxForms.SelectedIndex);
            }
            UpdateListItems();
        }

        private void btnRemoveItem_Click(object sender, EventArgs e)
        {
            RemoveForm();
        }

        private void rdbOption1_CheckedChanged(object sender, EventArgs e)
        {
            grpOptions.Enabled = true;
        }

        private void rdbOption2_CheckedChanged(object sender, EventArgs e)
        {
            grpOptions.Enabled = false;
        }

        private void rdbOption11_CheckedChanged(object sender, EventArgs e)
        {
            txtDLLPath.Enabled = true;
            btnSelectDLL.Enabled = true;
        }

        private void rdbOption12_CheckedChanged(object sender, EventArgs e)
        {
            txtDLLPath.Clear();
            txtDLLPath.Enabled = false;
            btnSelectDLL.Enabled = false;
        }

        private void rdbOption3_CheckedChanged(object sender, EventArgs e)
        {
            txtDLLPath.Clear();
            txtDLLPath.Enabled = false;
            btnSelectDLL.Enabled = false;
        }

        private void btnSelectDLL_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.Filter = "DLL (*.dll)|*.dll";
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.Multiselect = false;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    FileInfo fileInfo = new FileInfo(openFileDialog1.FileName);
                    txtDLLPath.Text = fileInfo.FullName;
                }
                catch (Exception ex)
                {
                }
            }
        }

        private void btnGenFeatures_Click(object sender, EventArgs e)
        {
            if (masterListForms.Count == 0)
            {
                MessageBox.Show("Please select the published infopath foms");
                return;
            }
            if (!rdbOption1.Checked && !rdbOption2.Checked && !rdbOption3.Checked)
            {
                MessageBox.Show("Please select one of the options in the common settigns group");
                return;
            }         
            if (rdbOption1.Checked)
                if (string.IsNullOrEmpty(txtDLLPath.Text))
                {
                    MessageBox.Show("Please select the DLL file common to all the forms");
                    return;
                }

            FormFeature formFeature = null;
            bool commonDLLPathProvided = rdbOption1.Checked;// && rdbOption11.Checked;
            bool hasCodeBehind = rdbOption2.Checked || rdbOption1.Checked;//(rdbOption1.Checked && rdbOption11.Checked) || commonDLLPathProvided;
            foreach (string form in masterListForms)
            {
                formFeature = new FormFeature();
                formFeature.FormPath = form;
                formFeature.HasCodeBehind = hasCodeBehind;
                formFeature.DllPath = commonDLLPathProvided ? txtDLLPath.Text.Trim() : "";
                formFeature.Title = (new System.IO.FileInfo(formFeature.FormPath)).Name;
                formFeature.Title = formFeature.Title.Substring(0, formFeature.Title.IndexOf("."));
                formFeature.FeatureID = Guid.NewGuid(); //.ToString().Replace("{","").Replace("}","")
                formFeatureList.Add(formFeature);
            }

            
            Thread procThread = new Thread(new ThreadStart(StartProcessing));
            //(new FormsFeatureManager()).ProcessForms(formFeatureList);
            txtInformation.Text = "Processing.....";
            txtInformation.Update();
            Application.DoEvents();
            procThread.IsBackground = true;
            procThread.Start();
            procThread.Join();
            txtInformation.Text = infoMessage + Environment.NewLine + Environment.NewLine;
            txtInformation.Text += "Processing completed."+ Environment.NewLine +"Feature folders are created at: "+ Environment.CurrentDirectory + "\\Output\\12\\TEMPLATE\\FEATURES\\";
        }

        private void StartProcessing()
        {
            FormsFeatureManager featureManager = new FormsFeatureManager();
            infoMessage = featureManager.ProcessForms(formFeatureList);
            //Thread.Sleep(500);
        }

        private void btnGenWSP_Click(object sender, EventArgs e)
        {
            SelectWSPName selectWSPName = new SelectWSPName();
            selectWSPName.ShowDialog();

            if (selectWSPName.WspName.Length > 0)
            {
                wspName = selectWSPName.WspName;
                txtInformation.Text = "Started building the WSP...";
                txtInformation.Update();
                Application.DoEvents();
                Thread procThread = new Thread(new ThreadStart(StartWSPProcessing));
                procThread.IsBackground = true;
                procThread.Start();
                procThread.Join();
                txtInformation.Text = "WSP creation completed." + Environment.NewLine + "WSP located at: " + Environment.CurrentDirectory + "\\Output";
            }
        }

        private void StartWSPProcessing()
        {
            (new FormsFeatureManager()).RunWSPBuilder(wspName);
        }

        private void btnInstallSol_Click(object sender, EventArgs e)
        {
            txtInformation.Text = "Installing the WSP...";
            txtInformation.Update();
            Application.DoEvents();

            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.EnableRaisingEvents = false;
            proc.StartInfo.FileName = "InstallWSP.bat";
            proc.StartInfo.Arguments = wspName;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.Start();

            txtInformation.Text = proc.StandardOutput.ReadToEnd();
            proc.WaitForExit();
        }

        private void btnActivateFeature_Click(object sender, EventArgs e)
        {
            SelectSiteCollectionForm selectSiteForm = new SelectSiteCollectionForm();
            selectSiteForm.ShowDialog();
            if (String.IsNullOrEmpty(selectSiteForm.SiteCollectionURL))
            {
                return; //throw new Exception("Site URL provided is empty");
            }

            txtInformation.Text = "Started activation process...";
            txtInformation.Update();
            Application.DoEvents();
            Thread procThread = new Thread(new ThreadStart(StartActivationProcess));
            procThread.IsBackground = true;
            procThread.Start();
            procThread.Join();
            txtInformation.Text = "Activation of the forms deployed is completed.";
        }

        private void StartActivationProcess()
        {
            try
            {
                using (SPSite siteCollection = new SPSite(activationSiteUrl))
                {
                    foreach (FormFeature form in formFeatureList)
                    {
                        try
                        {
                            siteCollection.Features.Add(form.FeatureID, true);
                        }
                        catch (Exception ex1)
                        {
                            //throw new Exception(ex1.Message);
                            MessageBox.Show("Failed activation: " + form.Title ); 
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnFormWorkflowPopup_Click(object sender, EventArgs e)
        {
            //InfoPathFormsWorkflowAssociator ipWFAssociator = new InfoPathFormsWorkflowAssociator();
            //ipWFAssociator.ShowDialog();
            ShareTools.WorkflowManager.ContentTypeBasedWorkflowManager ctWFAssociator = new ShareTools.WorkflowManager.ContentTypeBasedWorkflowManager();
            ctWFAssociator.ShowDialog();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            About abt = new About();
            abt.ShowDialog();
        }

        private void listBoxForms_DragEnter(object sender, DragEventArgs e)
        {
            if ((e.AllowedEffect & DragDropEffects.Link) != 0 && e.Data.GetDataPresent(System.Windows.Forms.DataFormats.FileDrop))// (typeof(string)))
                e.Effect = DragDropEffects.Link;
            else
            {
                
            }
        }

        private bool CheckAllInfoPathForms(string[] formsList)
        {
            for (int i = 0; i < formsList.Length; i++)
            {
                if (!formsList[i].EndsWith(".xsn"))
                    return false;
            }
            return true;
        }

        private void listBoxForms_DragDrop(object sender, DragEventArgs e)
        {
            object obj = e.Data.GetData(System.Windows.Forms.DataFormats.FileDrop);
            string[] formsList = obj as string[];
            if (CheckAllInfoPathForms(formsList))
            {
                LoadMasterListOfForms(formsList);
                UpdateListItems();
            }
            else
                MessageBox.Show("Check all the files selected are InfoPath Forms(.xsn) files.");
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            // Determine which link was clicked within the LinkLabel.
            this.linkLabel2.Links[linkLabel2.Links.IndexOf(e.Link)].Visited = true;

            // Display the appropriate link based on the value of the 
            // LinkData property of the Link object.
            string target = e.Link.LinkData as string;
            OpenLink(target);
        }
        private void OpenLink(string target)
        {
            // If the value looks like a URL, navigate to it.
            // Otherwise, display it in a message box.
            if (null != target)// && target.StartsWith("http"))
            {
                System.Diagnostics.Process.Start(target);
            }
            else
            {
                MessageBox.Show("Item clicked: " + target);
            }
        }

    }
}